package com.clp.protocol.iec104.iec104.apdu.apci;

import com.clp.protocol.core.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.iec104.iec104.definition.ApduType;
import com.clp.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;
import java.util.function.Consumer;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class SCtrlArea extends CtrlArea<SCtrlArea> {
    /**
     * 接收序号
     */
    private int recvSeq;

    @Override
    public SCtrlArea refreshFrom(ByteBuf buf) {
        buf.readShortLE(); // 跳过发送序号
        this.recvSeq = (buf.readShortLE() & 0xFFFF) >> 1;
        return this;
    }

    @Override
    public boolean isValid() {
        return recvSeq >= 0;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeByte(ApduType.SType.getTypeDef());
        buf.writeByte(0);
        buf.writeShortLE(recvSeq << 1);
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        byte[] recvSeq = ByteUtil.intToBytes2LE(this.recvSeq << 1);
        sb.append(byteFormat.format(recvSeq[0]));
        for (int i = 1; i < recvSeq.length; i++) {
            sb.append(byteSeparator).append(byteFormat.format(recvSeq[i]));
        }
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append("[").append(recvSeq).append("]");
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append("接收序号：").append(recvSeq);
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SCtrlArea that = (SCtrlArea) o;
        return recvSeq == that.recvSeq;
    }

    @Override
    public int hashCode() {
        return Objects.hash(recvSeq);
    }
}
